// 提供视频上传与转换的 API
// 使用 XMLHttpRequest 以便获取上传进度
import { getErrorMessage } from '@/utils/errorHandler'

/**
 * 上传视频并转换为 GIF
 * @param {FormData} formData 包含文件与参数的表单数据
 * @param {(progress:number)=>void} onProgress 进度回调（0-100）
 * @returns {Promise<any>} 后端统一响应 Result<ConversionResponseDTO>
 */
export function uploadAndConvert(formData, onProgress) {
  return new Promise((resolve, reject) => {
    const xhr = new XMLHttpRequest()
    xhr.open('POST', '/api/conversion/videoToGif/upload')

    // 进度回调
    if (xhr.upload && typeof onProgress === 'function') {
      xhr.upload.onprogress = (event) => {
        if (event.lengthComputable) {
          const percent = Math.round((event.loaded / event.total) * 100)
          try {
            onProgress(percent)
          } catch (_) {
            // 忽略回调内部异常
          }
        }
      }
    }

    xhr.onreadystatechange = () => {
      if (xhr.readyState !== 4) return
      const status = xhr.status
      let payload = null
      try {
        payload = xhr.responseText ? JSON.parse(xhr.responseText) : null
      } catch (e) {
        return reject(new Error('响应解析失败'))
      }

      if (status >= 200 && status < 300) {
        // 后端统一 Result 格式：{ code, message, data }
        if (payload && payload.code === 200) {
          resolve(payload)
        } else {
          // 使用错误码获取友好的错误消息
          const errorCode = payload && payload.code
          const errorMessage = payload && payload.message
          const friendlyMessage = getErrorMessage(errorCode, errorMessage)
          reject(new Error(friendlyMessage))
        }
      } else {
        reject(new Error('网络错误，稍后重试'))
      }
    }

    xhr.onerror = () => reject(new Error('网络错误，稍后重试'))
    xhr.send(formData)
  })
}

/**
 * 上传文件并转换为 SVG
 * @param {FormData} formData 包含文件与参数的表单数据
 * @returns {Promise<any>} 后端统一响应 Result<ConversionResponseDTO>
 */
export function uploadAndConvertToSvg(formData) {
  return new Promise((resolve, reject) => {
    const xhr = new XMLHttpRequest()
    xhr.open('POST', '/api/conversion/fileToSvg/upload')

    xhr.onreadystatechange = () => {
      if (xhr.readyState !== 4) return
      const status = xhr.status
      let payload = null
      try {
        payload = xhr.responseText ? JSON.parse(xhr.responseText) : null
      } catch (e) {
        return reject(new Error('响应解析失败'))
      }

      if (status >= 200 && status < 300) {
        // 后端统一 Result 格式：{ code, message, data }
        if (payload && payload.code === 200) {
          resolve(payload)
        } else {
          // 使用错误码获取友好的错误消息
          const errorCode = payload && payload.code
          const errorMessage = payload && payload.message
          const friendlyMessage = getErrorMessage(errorCode, errorMessage)
          reject(new Error(friendlyMessage))
        }
      } else {
        reject(new Error('网络错误，稍后重试'))
      }
    }

    xhr.onerror = () => reject(new Error('网络错误，稍后重试'))
    xhr.send(formData)
  })
}

/**
 * 上传 DOCX 并转换为 PDF
 * @param {FormData} formData 含文件与参数
 * @returns {Promise<any>}
 */
export function uploadDocxToPdf(formData) {
  return new Promise((resolve, reject) => {
    const xhr = new XMLHttpRequest()
    xhr.open('POST', '/api/conversion/docxToPdf/upload')

    xhr.onreadystatechange = () => {
      if (xhr.readyState !== 4) return
      const status = xhr.status
      let payload = null
      try {
        payload = xhr.responseText ? JSON.parse(xhr.responseText) : null
      } catch (e) {
        return reject(new Error('响应解析失败'))
      }

      if (status >= 200 && status < 300) {
        if (payload && payload.code === 200) {
          resolve(payload)
        } else {
          const errorCode = payload && payload.code
          const errorMessage = payload && payload.message
          const friendlyMessage = getErrorMessage(errorCode, errorMessage)
          reject(new Error(friendlyMessage))
        }
      } else {
        reject(new Error('网络错误，稍后重试'))
      }
    }

    xhr.onerror = () => reject(new Error('网络错误，稍后重试'))
    xhr.send(formData)
  })
}

/**
 * 上传图片并执行抠图
 * @param {FormData} formData 包含文件与参数的表单数据
 * @returns {Promise<any>} 后端统一响应 Result<ConversionImageMattingResponseDTO>
 */
export function uploadAndConvertImageMatting(formData) {
  return new Promise((resolve, reject) => {
    const xhr = new XMLHttpRequest()
    xhr.open('POST', '/api/conversion/imageMatting/upload')

    xhr.onreadystatechange = () => {
      if (xhr.readyState !== 4) return
      const status = xhr.status
      let payload = null
      try {
        payload = xhr.responseText ? JSON.parse(xhr.responseText) : null
      } catch (e) {
        return reject(new Error('响应解析失败'))
      }

      if (status >= 200 && status < 300) {
        // 后端统一 Result 格式：{ code, message, data }
        if (payload && payload.code === 200) {
          resolve(payload)
        } else {
          // 使用错误码获取友好的错误消息
          const errorCode = payload && payload.code
          const errorMessage = payload && payload.message
          const friendlyMessage = getErrorMessage(errorCode, errorMessage)
          reject(new Error(friendlyMessage))
        }
      } else {
        reject(new Error('网络错误，稍后重试'))
      }
    }

    xhr.onerror = () => reject(new Error('网络错误，稍后重试'))
    xhr.send(formData)
  })
}

/**
 * 上传手动抠图结果
 * @param {FormData} formData 包含文件与参数的表单数据
 * @returns {Promise<any>} 后端统一响应 Result<ConversionImageMattingResponseDTO>
 */
export function uploadManualMattingResult(formData) {
  return new Promise((resolve, reject) => {
    const xhr = new XMLHttpRequest()
    xhr.open('POST', '/api/conversion/imageMatting/uploadManual')

    xhr.onreadystatechange = () => {
      if (xhr.readyState !== 4) return
      const status = xhr.status
      let payload = null
      try {
        payload = xhr.responseText ? JSON.parse(xhr.responseText) : null
      } catch (e) {
        return reject(new Error('响应解析失败'))
      }

      if (status >= 200 && status < 300) {
        // 后端统一 Result 格式：{ code, message, data }
        if (payload && payload.code === 200) {
          resolve(payload)
        } else {
          // 使用错误码获取友好的错误消息
          const errorCode = payload && payload.code
          const errorMessage = payload && payload.message
          const friendlyMessage = getErrorMessage(errorCode, errorMessage)
          reject(new Error(friendlyMessage))
        }
      } else {
        reject(new Error('网络错误，稍后重试'))
      }
    }

    xhr.onerror = () => reject(new Error('网络错误，稍后重试'))
    xhr.send(formData)
  })
}

